﻿using System;
using System.Data.Common;
using System.Collections.Generic;

using DreamCube.Foundation.Basic.Utility;

namespace DreamCube.Framework.DataAccess.Basic
{
    public static class DBObjectHelper
    {
        /// <summary>
        /// 查询数据库获取Model集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="db"></param>
        /// <param name="column"></param>
        /// <param name="strWhere"></param>
        /// <param name="orderBy"></param>
        /// <returns></returns>
        public static List<T> GetModelList<T>(Database db, String tableName, String column = "*", String strWhere = "", String orderBy = "")
            where T : ModelObject, new()
        {
            return db.GetModelList<T>(tableName, column, strWhere, orderBy);
        }

        /// <summary>
        /// 批量保存所有的DBObjectX对象到数据库中
        /// </summary>
        /// <param name="dbObjectXList"></param>
        /// <param name="doInTransaction">是否在事务中执行操作，默认true，启用事务进行插入操作</param>
        /// <returns></returns>
        public static Boolean SaveDBObjectList(List<DBObject> dbObjectXList, Boolean doInTransaction = true, Database db = null)
        {
            if (dbObjectXList == null || dbObjectXList.Count == 0) return false;
            if (db == null) db = DBManager.GetDBByName();
            //如果是一条记录的话，则不需要考虑是否启用事务
            if (dbObjectXList.Count == 1) 
                return dbObjectXList[0].SaveToDB();
            if (doInTransaction)
            {
                DbCommand command = db.CreateCommand();
                DbConnection conn = db.CreateConnection(false);
                //启动事务支出
                DbTransaction trans = conn.BeginTransaction();
                command.Connection = conn;
                command.Transaction = trans;
                try
                {
                    conn.Open();
                    for (Int32 i = 0, j = dbObjectXList.Count; i < j; i++)
                        dbObjectXList[i].SaveToDB(command);
                    //提交事务
                    trans.Commit();
                    return true;
                }
                catch (Exception)
                {
                    trans.Rollback();
                    throw;
                }
            }
            else
            {
                for (Int32 i = 0, j = dbObjectXList.Count; i < j; i++)
                    dbObjectXList[i].SaveToDB();
            }
            return true;
        }
    }
}
